<template>
  <div class="favorites-page min-h-screen bg-gray-50">
    <!-- 页面头部 -->
    <div class="bg-white shadow-sm border-b border-gray-200">
      <div class="container mx-auto px-4 py-6">
        <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
          <div>
            <h1 class="text-2xl font-bold text-gray-900">
              我的收藏
            </h1>
            <p class="text-sm text-gray-600 mt-1">
              共 {{ favoritesStore.favoritesCount }} 个收藏
              <span
                v-if="favoritesStore.favoriteStats.recentCount > 0"
                class="ml-2"
              >
                · 最近7天新增 {{ favoritesStore.favoriteStats.recentCount }} 个
              </span>
            </p>
          </div>
          
          <!-- 操作按钮 -->
          <div class="flex items-center gap-3">
            <button
              v-if="favoritesStore.hasSelectedItems"
              class="px-4 py-2 text-sm font-medium text-red-600 bg-red-50 border border-red-200 rounded-lg hover:bg-red-100 transition-colors"
              @click="handleBatchDelete"
            >
              <TrashIcon class="w-4 h-4 inline-block mr-1" />
              删除 ({{ favoritesStore.selectedItems.size }})
            </button>
            
            <button
              v-if="!favoritesStore.isEmpty"
              class="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors"
              @click="favoritesStore.exportFavorites"
            >
              <ArrowDownTrayIcon class="w-4 h-4 inline-block mr-1" />
              导出
            </button>
          </div>
        </div>
      </div>
    </div>

    <div class="container mx-auto px-4 py-6">
      <!-- 搜索和筛选 -->
      <div
        v-if="!favoritesStore.isEmpty"
        class="bg-white rounded-lg shadow-sm border border-gray-200 p-4 mb-6"
      >
        <div class="flex flex-col sm:flex-row gap-4">
          <!-- 搜索框 -->
          <div class="flex-1">
            <div class="relative">
              <MagnifyingGlassIcon class="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400" />
              <input
                v-model="searchQuery"
                type="text"
                placeholder="搜索条文编号或标题..."
                class="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                @input="handleSearch"
              >
            </div>
          </div>
          
          <!-- 批量操作 -->
          <div class="flex items-center gap-2">
            <label class="flex items-center">
              <input
                type="checkbox"
                :checked="favoritesStore.allItemsSelected"
                :indeterminate="favoritesStore.hasSelectedItems && !favoritesStore.allItemsSelected"
                class="w-4 h-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500"
                @change="favoritesStore.toggleSelectAll"
              >
              <span class="ml-2 text-sm text-gray-700">全选</span>
            </label>
            
            <button
              v-if="favoritesStore.hasSelectedItems"
              class="text-sm text-gray-600 hover:text-gray-800"
              @click="favoritesStore.clearSelection"
            >
              取消选择
            </button>
          </div>
        </div>
      </div>

      <!-- 收藏统计 -->
      <div
        v-if="!favoritesStore.isEmpty && showStats"
        class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6"
      >
        <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
          <div class="flex items-center">
            <div class="w-8 h-8 bg-blue-100 rounded-lg flex items-center justify-center">
              <HeartIcon class="w-4 h-4 text-blue-600" />
            </div>
            <div class="ml-3">
              <p class="text-sm font-medium text-gray-900">
                总收藏
              </p>
              <p class="text-2xl font-bold text-blue-600">
                {{ favoritesStore.favoriteStats.totalCount }}
              </p>
            </div>
          </div>
        </div>
        
        <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
          <div class="flex items-center">
            <div class="w-8 h-8 bg-green-100 rounded-lg flex items-center justify-center">
              <PlusIcon class="w-4 h-4 text-green-600" />
            </div>
            <div class="ml-3">
              <p class="text-sm font-medium text-gray-900">
                本周新增
              </p>
              <p class="text-2xl font-bold text-green-600">
                {{ favoritesStore.favoriteStats.recentCount }}
              </p>
            </div>
          </div>
        </div>
        
        <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
          <div class="flex items-center">
            <div class="w-8 h-8 bg-purple-100 rounded-lg flex items-center justify-center">
              <BookmarkIcon class="w-4 h-4 text-purple-600" />
            </div>
            <div class="ml-3">
              <p class="text-sm font-medium text-gray-900">
                涉及章节
              </p>
              <p class="text-2xl font-bold text-purple-600">
                {{ Object.keys(favoritesStore.favoriteStats.byPart).length }}
              </p>
            </div>
          </div>
        </div>
      </div>

      <!-- 收藏列表 -->
      <div class="space-y-4">
        <!-- 加载状态 -->
        <div
          v-if="favoritesStore.loading"
          class="flex justify-center py-12"
        >
          <LoadingSpinner size="large" />
        </div>

        <!-- 空状态 -->
        <div
          v-else-if="favoritesStore.isEmpty"
          class="empty-state"
        >
          <div class="text-center py-12">
            <HeartIcon class="w-16 h-16 text-gray-400 mx-auto mb-4" />
            <h3 class="text-lg font-medium text-gray-900 mb-2">
              暂无收藏条文
            </h3>
            <p class="text-gray-600 mb-6">
              开始浏览民法典条文并添加收藏吧
            </p>
            <router-link
              to="/browse"
              class="inline-flex items-center px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
            >
              <MagnifyingGlassIcon class="w-4 h-4 mr-2" />
              浏览条文
            </router-link>
          </div>
        </div>

        <!-- 收藏条文列表 -->
        <div
          v-else
          class="space-y-3"
        >
          <div
            v-for="favorite in favoritesStore.filteredFavorites"
            :key="favorite.article_number"
            class="favorite-item bg-white rounded-lg shadow-sm border border-gray-200 p-4 hover:shadow-md transition-shadow"
          >
            <div class="flex items-start gap-4">
              <!-- 选择框 -->
              <div class="flex items-center pt-1">
                <input
                  type="checkbox"
                  :checked="favoritesStore.selectedItems.has(favorite.article_number)"
                  class="w-4 h-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500"
                  @change="favoritesStore.toggleSelectItem(favorite.article_number)"
                >
              </div>
              
              <!-- 条文信息 -->
              <div class="flex-1 min-w-0">
                <div class="flex items-start justify-between gap-4">
                  <div class="flex-1">
                    <router-link
                      :to="`/article/${favorite.article_number}`"
                      class="block group"
                    >
                      <h3 class="text-sm font-semibold text-blue-600 group-hover:text-blue-800 mb-1">
                        {{ favorite.article_number }}
                      </h3>
                      <p class="text-gray-900 text-sm leading-relaxed line-clamp-2 group-hover:text-gray-700">
                        {{ favorite.title }}
                      </p>
                    </router-link>
                    
                    <!-- 元信息 -->
                    <div class="flex items-center gap-4 mt-3 text-xs text-gray-500">
                      <span
                        v-if="favorite.part"
                        class="inline-flex items-center"
                      >
                        <BookOpenIcon class="w-3 h-3 mr-1" />
                        {{ favorite.part }}
                      </span>
                      <span class="inline-flex items-center">
                        <ClockIcon class="w-3 h-3 mr-1" />
                        {{ formatDate(favorite.created_at) }}
                      </span>
                    </div>
                  </div>
                  
                  <!-- 操作按钮 -->
                  <div class="flex items-center gap-2">
                    <router-link
                      :to="`/article/${favorite.article_number}`"
                      class="p-2 text-gray-400 hover:text-blue-600 rounded-lg hover:bg-blue-50 transition-colors"
                      title="查看详情"
                    >
                      <EyeIcon class="w-4 h-4" />
                    </router-link>
                    
                    <button
                      class="p-2 text-gray-400 hover:text-red-600 rounded-lg hover:bg-red-50 transition-colors"
                      title="取消收藏"
                      @click="handleRemoveFavorite(favorite.article_number)"
                    >
                      <HeartIcon class="w-4 h-4 fill-current" />
                    </button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 分页 -->
        <div
          v-if="favoritesStore.pagination.pages > 1"
          class="flex justify-center mt-8"
        >
          <nav class="flex items-center gap-2">
            <button
              v-for="page in visiblePages"
              :key="page"
              :class="[
                'px-3 py-2 text-sm font-medium rounded-lg transition-colors',
                page === favoritesStore.pagination.page
                  ? 'bg-blue-600 text-white'
                  : 'text-gray-700 bg-white border border-gray-300 hover:bg-gray-50'
              ]"
              @click="loadPage(page)"
            >
              {{ page }}
            </button>
          </nav>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { useFavoritesStore } from '@/stores/favorites'
import { useAppStore } from '@/stores/app'
import {
  HeartIcon,
  MagnifyingGlassIcon,
  TrashIcon,
  ArrowDownTrayIcon,
  EyeIcon,
  BookOpenIcon,
  ClockIcon,
  PlusIcon,
  BookmarkIcon
} from '@heroicons/vue/24/outline'
import LoadingSpinner from '@/components/common/LoadingSpinner.vue'

// Stores
const favoritesStore = useFavoritesStore()
const appStore = useAppStore()

// 响应式数据
const searchQuery = ref('')
const showStats = ref(true)

// 计算属性
const visiblePages = computed(() => {
  const current = favoritesStore.pagination.page
  const total = favoritesStore.pagination.pages
  const pages = []
  
  const start = Math.max(1, current - 2)
  const end = Math.min(total, current + 2)
  
  for (let i = start; i <= end; i++) {
    pages.push(i)
  }
  
  return pages
})

// 方法
const handleSearch = () => {
  favoritesStore.setSearchQuery(searchQuery.value)
}

const handleRemoveFavorite = async (articleNumber) => {
  if (confirm('确定要取消收藏这个条文吗？')) {
    try {
      await favoritesStore.removeFavorite(articleNumber)
    } catch (err) {
      // 错误已在store中处理
    }
  }
}

const handleBatchDelete = async () => {
  const count = favoritesStore.selectedItems.size
  if (confirm(`确定要批量取消收藏这 ${count} 个条文吗？`)) {
    try {
      await favoritesStore.batchRemoveFavorites()
    } catch (err) {
      // 错误已在store中处理
    }
  }
}

const loadPage = (page) => {
  favoritesStore.loadFavorites(page)
}

const formatDate = (dateString) => {
  try {
    const date = new Date(dateString)
    const now = new Date()
    const diff = now.getTime() - date.getTime()
    const days = Math.floor(diff / (1000 * 60 * 60 * 24))
    
    if (days === 0) {
      return '今天'
    } else if (days === 1) {
      return '昨天'
    } else if (days < 7) {
      return `${days}天前`
    } else {
      return date.toLocaleDateString('zh-CN')
    }
  } catch {
    return '未知时间'
  }
}

// 生命周期
onMounted(() => {
  console.log('[FavoritesView] 页面挂载，开始加载收藏')
  favoritesStore.loadFavorites()
})

onUnmounted(() => {
  favoritesStore.reset()
  console.log('[FavoritesView] 页面卸载，重置收藏状态')
})

// 监听搜索查询变化
watch(searchQuery, (newQuery) => {
  console.log('[FavoritesView] 搜索查询变化:', newQuery)
  favoritesStore.setSearchQuery(newQuery)
}, { debounce: 300 })
</script>

<style scoped>
.favorite-item {
  transition: all 0.2s ease;
}

.favorite-item:hover {
  transform: translateY(-1px);
}

/* 自定义复选框样式 */
input[type="checkbox"]:indeterminate {
  background-color: #3b82f6;
  border-color: #3b82f6;
}

input[type="checkbox"]:indeterminate::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 8px;
  height: 2px;
  background-color: white;
}
</style>
